﻿
using Xacml.Core.Interfaces;
using Xacml.Core.Policy;
using System.Collections;

namespace Xacml.Core.Runtime
{
  public class RuleCombiningAlgorithmPermitOverrides : IRuleCombiningAlgorithm
  {
    public Decision Evaluate(EvaluationContext context, RuleCollection rules)
    {
      Decision decision = Decision.Indeterminate;
      bool flag1 = false;
      bool flag2 = false;
      bool flag3 = false;
      context.Trace("Evaluating rules...");
      context.AddIndent();
      try
      {
        foreach (Rule rule in (CollectionBase) rules)
        {
          decision = rule.Evaluate(context);
          context.TraceContextValues();
          if (decision == Decision.Deny)
          {
            flag3 = true;
          }
          else
          {
            if (decision == Decision.Permit)
            {
              decision = Decision.Permit;
              return decision;
            }
            if (decision != Decision.NotApplicable && decision == Decision.Indeterminate)
            {
              flag1 = true;
              if (rule.RuleDefinition.Effect == Effect.Permit)
                flag2 = true;
            }
          }
        }
        if (flag2)
        {
          decision = Decision.Indeterminate;
          return decision;
        }
        if (flag3)
        {
          decision = Decision.Deny;
          return decision;
        }
        if (flag1)
        {
          decision = Decision.Indeterminate;
          return decision;
        }
        decision = Decision.NotApplicable;
        return decision;
      }
      finally
      {
        context.Trace("Rule combination algorithm: {0}", (object) decision.ToString());
        context.RemoveIndent();
      }
    }
  }
}
